import React,{useState,useEffect,useReducer} from "react";
import {View,Text,Image,ScrollView,StyleSheet } from "react-native";
import {connect, ConnectedProps} from 'react-redux';
import {RootState} from '@/models/index';
import {getWidth} from "../../utils/index";
import Touchable from "../../components/Touchable";
import IconFont,{IconNames} from "../../assets/iconfont";
import Toast from 'react-native-root-toast';
import {IUserInfo} from '@/models/user';
import AsyncStorage from '@react-native-async-storage/async-storage';
const mapStateToProps = ({users,loading}: RootState) => {
  return {
    currentUser1: users?.user,
    // 在触发getGoodsList方法时加上加载效果
    loading: loading.effects['articals/likeArticals'],
  };
};
const connector = connect(mapStateToProps);
type ModelState = ConnectedProps<typeof connector>;
interface IProps extends ModelState {
  navigation: {navigate: any};
  route:any
}
const ImageInfo = (props:IProps) => {
  const {route,navigation,dispatch,currentUser1} = props;
  const [color,setColor] = useState<"yellow"|"noColor">( currentUser1 ? currentUser1[0] ? currentUser1[0].Like?.indexOf(route.params.selectItem._id) === -1 ? "noColor" : "yellow":"noColor":"noColor");
  useEffect(()=>{
    console.log("111s")
    let color:"yellow"|"noColor" = currentUser1 ? currentUser1[0] ? currentUser1[0].Like?.indexOf(route.params.selectItem._id) === -1 ? "noColor" : "yellow":"noColor":"noColor"
    setColor(color);
  })
  const handleBigImage = (url:string) => {
    console.log("点击了放大图片",url);
    navigation.navigate("BigImage",{
      url:url
    })
  }
  return (
    <View style={styles.editUserInfo}>
          <ScrollView style={styles.iBox}>
            {
                <View style={styles.iItem}>
                  <View style={styles.bottomBox}>
                    <View>
                    <Text style={styles.title}>{route.params.selectItem.artical_title}</Text>
                    </View>
                    <View style={styles.headers}>
                    <Touchable style={styles.info} onPress={()=>{
                      console.log("route.params.selectItem.owner_id",route.params.selectItem.owner_id)
                      navigation.navigate("PrincipalSheet",{
                        selectedId:route.params.selectItem.owner_id
                      })
                    }}>
                    <Image
                      source={{uri: route.params.selectItem.scurpture}}
                      style={styles.scurpture}></Image>
                    <View>
                      <Text>{ route.params.selectItem.publish_time} </Text>
                      <Text>{ route.params.selectItem.username} </Text>
                    </View>
                    </Touchable>
                    <Touchable style={styles.have} onPress={()=> {
                      // 得先判断是否登录
                      if(JSON.stringify(currentUser1) === "[]"){
                        Toast.show('请先登录后收藏', {
                          position: Toast.positions.CENTER,
                          duration: Toast.durations.LONG,
                          shadow: true,
                          animation: true,
                        });
                        navigation.navigate("Login");
                        // 如果先不登录访问这个页面， 那么页面加载了，再登录，就不会执行初始化收藏的函数，所以在回来还得再执行
                        return;
                      }
                      if(color === "yellow") {
                        dispatch({
                          type: 'users/cancelLikeArtical',
                          payload: {
                            formData: {
                              user_id:currentUser1&& currentUser1[0]._id ? currentUser1[0]._id : '',
                              artical_id:route.params.selectItem._id
                            },
                            callback: () => {
                              setColor("noColor");
                              dispatch({
                                type: 'users/getCurrentUser',
                                payload: {
                                  user_id: currentUser1&& currentUser1[0]._id ? currentUser1[0]._id : '',
                                  callback: (data: IUserInfo[]) => {
                                    console.log('取消收藏文章拿到了data', data);
                                    data[0] &&
                                      AsyncStorage.setItem(
                                        'currentUserInfo',
                                        JSON.stringify(data[0]),
                                      );
                                    Toast.show('取消收藏成功', {
                                      position: Toast.positions.CENTER,
                                      duration: Toast.durations.LONG,
                                      shadow: true,
                                      animation: true,
                                    });
                                    route.params.handleClick && route.params.handleClick()
                                  },
                                },
                              });
                            },
                          },
                        });
                      }else {
                        dispatch({
                          type: 'users/likeArticals',
                          payload: {
                            formData: {
                              user_id:currentUser1&& currentUser1[0]._id ? currentUser1[0]._id : '',
                              artical_id:route.params.selectItem._id
                            },
                            callback: () => {
                              setColor("yellow");
                              // 更新本地的currentUserInfo
                              dispatch({
                                type: 'users/getCurrentUser',
                                payload: {
                                  user_id: currentUser1&& currentUser1[0]._id ? currentUser1[0]._id : '',
                                  callback: (data: IUserInfo[]) => {
                                    console.log('点赞文章拿到了data', data);
                                    data[0] &&
                                      AsyncStorage.setItem(
                                        'currentUserInfo',
                                        JSON.stringify(data[0]),
                                      );
                                    Toast.show('收藏成功', {
                                      position: Toast.positions.CENTER,
                                      duration: Toast.durations.LONG,
                                      shadow: true,
                                      animation: true,
                                    });
                                    route.params.handleClick && route.params.handleClick()
                                  },
                                },
                              });
                            },
                          },
                        });
                      }
                    }} >
                       <IconFont name="icon-lanling-ershoujiaoyi" size={22} color={color==="yellow" ? "#A75E5E" : "#ccc"} />
                     </Touchable>
                    </View>
                  </View>
                  <View style={styles.imageBox}>
                    {route.params.selectItem && route.params.selectItem.artical_images &&
                      route.params.selectItem.artical_images.map((image:any)=> {
                        return (
                         <Touchable key={image.i_url} style={styles.bigImage} onPress={()=>{
                          handleBigImage(image.i_url)
                         }}>
                           <Image
                            source={{uri: image.i_url}}
                            style={styles.image}></Image>
                         </Touchable>
                        );
                      })}
                  </View>
                  <Text style={styles.detail}>{route.params.selectItem.artical_detail}</Text>
                </View> 
            }
          </ScrollView>
    </View>
  )
}
const styles = StyleSheet.create({
  editUserInfo:{
    flex:1,
    // backgroundColor:"#fff",
    paddingHorizontal:10,
  },
  iBox: {
    // backgroundColor:"#fff",
  },
  iItem: {
    marginVertical: 5,
    borderRadius: 5,
    backgroundColor: '#fff',
    paddingTop: 10,
    width:"100%",
  },
  imageBox: {
    display: 'flex',
    flexDirection: 'row',
    flexWrap: 'wrap',
    paddingHorizontal: 8,
    width:"100%",
  },
  bigImage:{
    width: "31%",
    height: 100,
    borderRadius: 5,
    marginHorizontal: "1%",
    marginVertical: 4,
  },
  image: {
    width: "100%",
    height: 100,
    borderRadius: 5,
  },
  scurpture: {
    width: 50,
    height: 50,
    borderRadius: 50,
    marginRight: 10,
  },
  bottomBox: {
    display: 'flex',
    padding: 10,
    backgroundColor:"#fff",
    borderRadius: 5,
  },
  title: {
    fontSize: 20,
    padding:10,
    fontWeight: '700',
  },
  detail:{
    padding:10,
    fontSize:16
  },
  info: {
    width:"88%",
    display:"flex",
    flexDirection:"row",
    alignItems:"center"
  },
  headers:{
    display:"flex",
    flexDirection:"row",
    alignItems:"center"
  },
  have:{
    width:"12%"
  }
})
export default connector(ImageInfo);